package com.gjt.http;

import com.gjt.URI_URL.QueryString;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.security.Permission;

/**
 * Created with Intel IDEA.
 *
 *  简单的做一个提交表单的功能(向服务器写入数据)
 *
 *
 *
 * @Auther: gjt
 * @Date: 2024/4/7 4:04
 */
public class FormPoster {

    private URL url;

    // 拼装url 的查询字符串类
    private QueryString query = new QueryString();

    public FormPoster(URL url) {
        if(!url.getProtocol().toLowerCase().startsWith("http")){
            throw new IllegalArgumentException(" Posting only works for http URLs");
        }

        this.url = url;
    }

    public void add(String key , String value){
        query.add(key,value);
    }

    public InputStream post() throws IOException {

        // 打开连接，准备post
        URLConnection urlConnection = url.openConnection();
        String s = URLConnection.guessContentTypeFromName("html");
//        String s1 = URLConnection.guessContentTypeFromStream(urlConnection.getInputStream());
        System.out.println(s+"名字");
//        System.out.println(s1+"名字1");
        urlConnection.setDoOutput(true);

        try(OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream(),"UTF-8")){

            // post行，Content-type首部和Content-length首部 由URLConnection 发送。我们只发送数据
            out.write(query.toString());
            out.write("\r\n");
            out.flush();
        }catch (IOException e){
            e.printStackTrace();
        }

        // 返回响应
        return urlConnection.getInputStream();
    }

    public static void main(String[] args) {
        URL url = null;
        if(args.length > 0){
            try{
                url = new URL(args[0]);
            }catch ( IOException e){
                e.printStackTrace();
            }
        }else {
            try{
                url = new URL("http://www.cafeaulait.org/books/jnp4/postquery.phtml");
                URLConnection urlConnection = url.openConnection();

                // 在尝试连接一个url 之前可以检测是否允许连接 （果如是null，则不需要任何权限）
                Permission permission = urlConnection.getPermission();
                System.out.println("----------"+permission.getActions()+permission.getName());

            }catch (IOException ex){
                ex.printStackTrace();
            }
        }

        FormPoster poster = new FormPoster(url);
        poster.add("name","gjt");
        poster.add("age","12");

        try(InputStream in = poster.post()){
            int length = in.available();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            char[] list = new char[length];
            int start = 0;

            while (start < length){
                start += reader.read(list, start, length - start);
                System.out.println(list);
                // 流结束
                if(start == -1)break;
            }

        }catch (IOException e){
            e.printStackTrace();
        }

    }

}


